import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import ReactDOM from 'react-dom';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import SelectDeptTree from '@/components/SelectDeptTree';
import OrganTreeCreateForm from './OrganTreeCreateForm'; //新增表单
import OrganTreeUpdateForm from './OrganTreeUpdateForm'; //编辑表单
import styles from './ProOrganList.less';
import '@/assets/iconfont/iconfont';
import $ from 'jquery';
import 'orgchart';
import 'orgchart/dist/css/jquery.orgchart.css';
import '@/assets/iconfont/iconfont';
import {
    Row,
    Col,
    Form,
    Input,
    Select,
    Button,
    message,
    Upload,
    Icon,
    Card,
    DatePicker,
    InputNumber,
    Cascader,
    Modal
} from 'antd';
const FormItem = Form.Item;
const { confirm } = Modal;
const datascource = {
  dept_name: '某公司',
  name: '王某某',
  id: '1',
  key: '1',
  children: [
    {
      dept_name: '财务部',
      name: '李某某',
      id: '2',
      key: '2',
      children: [],
    },
    {
      dept_name: '研发部',
      name: '钱某某',
      id: '3',
      key: '3',
      children: [
        {
          dept_name: '研发部分支1',
          name: '张某某',
          id: '5',
          key: '5',
          children: [],
        },
        {
          dept_name: '研发部分支2',
          name: '姜某某',
          id: '6',
          key: '6',
          children: [],
        },
      ],
    },
    {
      dept_name: '销售部',
      name: '王某某',
      id: '4',
      key: '4',
      children: [],
    },
  ],
};
var nodeTemplate = function (data) {

        var str = `<div class="${styles.organ_box}">
                    <div class="${styles.dept_name}">${data.dept_name}</div>
                    <div class="${styles.name}">${data.name}</div>
                    <svg id="organAdd" class="${styles.icon} ${styles.organAdd}" aria-hidden="true">
                      <use id="organAdd" xlink:href="#icon-jiahao1"></use>
                    </svg>
                    <svg id="organEdit" class="${styles.icon} ${styles.organEdit}" aria-hidden="true">
                      <use id="organEdit" xlink:href="#icon-bianji"></use>
                    </svg>
                    <svg id="organDelete" class="${styles.icon} ${styles.organDelete}" aria-hidden="true">
                      <use id="organDelete" xlink:href="#icon-shanchu"></use>
                    </svg>
                  </div>`;
        return str;

};

/* eslint react/no-multi-comp:0 */
@connect(({ prodept, loading }) => ({
    prodept,
    loading: loading.models.prodept,
}))

@Form.create()
class StaffCreateForm extends PureComponent {

	state = {
	   file: null,
	   imageUrl: null,
	   flag: "1",
	   visible: false,
	   visiblePhoto: false,
	   photoNum: 0,
	   requestModelName:"prodept",
	   getDeptTreeBySelectTree: "",
	   staffName: "",
	   staffId: "",
     modalVisible: false,
     updateModalVisible: false,
     updateFormValues: {},
	};


  componentDidMount() {
    const options = {
      data: datascource, // 数据源
      depth: 3,
      pan: true, //鼠标拖动组织架构图
   // zoom: true, //滚轮放大缩小组织架构图
      direction: 'T2B', //控制结构图方向
      nodeContent: 'title',
      nodeTemplate: nodeTemplate,
      createNode: this.callbackFunction, //渲染节点的回调函数
      // toggleSiblingsResp: true, // 允许用户收缩展开兄弟节点
      visibleLevel: 3, // 默认展开三级
      dropCriteria: this.dropFunction, //自定义拖拽OrgChart节点
      draggable: true, //拖拽OrgChart节点,
      // initCompleted: this.initFunction
    };
    $(this.orgTree).orgchart(options);
  }

  //自定义拖拽OrgChart节点
  dropFunction = ($node1,$node2,$node3)=> {

  }

  //渲染节点的回调函数
  callbackFunction = ($node,data) => {
    console.log($node);
  	console.log(data);
    $($node).find('.bottomEdge').text("+");
    //注册鼠标进入事件
    $($node).mouseover((event) => {
      $("#"+ event.currentTarget.id).find('svg').show();
    });

    //注册鼠标离开事件
    $($node).mouseout((event) => {
      $("#"+ event.currentTarget.id).find('svg').hide();
    });

    //注册点击事件
    $($node).click((event) => {
      // console.log(event.target.id);
      // console.log(event.currentTarget);
      switch(event.target.id) {
          case "organAdd":
            this.handleModalVisible(true);
            break;
          case "organEdit":
            this.handleUpdateModalVisible(true);
            break;
          case "organDelete":
            this.handleDeleteRecord(event.currentTarget.id);
            break;
      }
    });
  };

  //新增部门
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  //编辑部门
  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      updateFormValues: record || {},
    });
  };

  //删除部门
  handleDeleteRecord = record => {
      const { dispatch } = this.props;
      const bodyDom = document.getElementsByTagName('body');
      const dom = ReactDOM.findDOMNode(bodyDom[0]);
      $(dom).css('overflow','hidden');
      confirm({
  		    title: '您确定要删除此部门吗?',
  		    okText: '确认',
          centered: true,
  		    cancelText: '取消',
  		    onOk() {
            $(dom).css('overflow','auto');
  		    },
  		    onCancel() {
            $(dom).css('overflow','auto');
          },
  		});
  };

	selectedDeptTreeValue = (deptRecord) => {
		this.setState({
			getDeptTreeBySelectTree: deptRecord
		})
	}

	beforeUpload = file => {
			console.log(file);

			this.setState({
	        file:file,
		  });

			if(window.FileReader) {
		      const reader = new FileReader();

		      reader.readAsDataURL(file);

				  reader.addEventListener('load', () => {

				  this.setState({
	          imageUrl:reader.result,
	          loading: false,
	          photoNum: 1
	      	})

				  });
			}

		  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.tyle === 'image/jpg';
		  if (!isJpgOrPng) {
		    message.error('You can only upload JPG/PNG file!');
		  }
		  const isLt2M = file.size / 1024 / 1024 < 2;
		  if (!isLt2M) {
		    message.error('Image must smaller than 2MB!');
		  }
		  return isJpgOrPng && isLt2M;
	}

 	onChange = (value) => {

	};

	handleChange = (value,e) => {
		const { dispatch } = this.props;
		this.setState({
			flag: value
		})
	};

	handleUpdate = e => {
	    this.setState({
	      visible: false,
	    });
	    router.push({
			  pathname: '/staff/updatestaff',
			  query: {
			    id: this.state.staffId,
			  },
			});
	};

	handleAdd = e => {
	    this.setState({
	      visible: false,
	    });
	};

  handleSubmit = (event) => {
	    event.preventDefault();

	    const { dispatch,form } = this.props;
	    const { getDeptTreeBySelectTree } = this.state;

	    form.validateFields(async(error, values) => {
	      	if (!error) {
	      		form.resetFields();
	      		values.entry_time = moment(values.entry_time._d).format("YYYY-MM-DD");
	      		if(values.date_of_birth) {
	      			values.date_of_birth = moment(values.date_of_birth._d).format("YYYY-MM-DD");
	      		}
						if(values.become_worker_time) {
							values.become_worker_time = moment(values.become_worker_time._d).format("YYYY-MM-DD");
						}
						if(getDeptTreeBySelectTree) {
							values.dept_id = getDeptTreeBySelectTree.triggerNode.props.dataRef.dept_id;
							values.dept = getDeptTreeBySelectTree.triggerNode.props.dataRef.title;
						}
						const bodymap = {
              pname: values.pname,
              phone: values.phone,
              gender:values.gender,
              idcard:values.idcard,
              date_of_birth: values.date_of_birth,
              place_of_origin: values.place_of_origin,
              place_of_domicile: values.place_of_domicile,
              email: values.email,
              emergency_contact_name: values.emergency_contact_name,
              emergency_contact_phone: values.emergency_contact_phone,
              bank_card_number: values.bank_card_number,
              open_bank: values.open_bank,
              entry_time: values.entry_time,
              dept: values.dept,
              dept_id: values.dept_id,
              post: values.post,
              from_of_employment: values.from_of_employment,
              become_worker_time: values.become_worker_time,
              become_worker_type: values.become_worker_type,
              management_form: values.management_form,
              job_number: values.job_number,
              working_city: values.working_city
           	};
           	const formData = new FormData();
           	console.log(this.state.file);
            formData.append('uploadfile', this.state.file);
            console.log(JSON.stringify(bodymap));
		    		formData.append('bodymap', JSON.stringify(bodymap));
		        await dispatch({
	              	type: 'prostaff/insert_for_staff',
	              	payload: {
											formdata: formData
	              	},
	              	callback:(res) => {
						        	if(res.success) {
												message.success('添加成功');
												this.setState({
										      visible: true,
										      staffName: res.datarecord.pname,
										      staffId: res.datarecord.id
										    });
						        	}else {
					        			message.success('添加失败');
						        	}
			  					}
	          });
		    }else{
		        return false;
		    }

	    })

	}

  //关闭继续添加弹窗
  handleStaffCancel = () => {
  		this.setState({
	      visible: false,
	    });
  }

	handleCancel = () => {
			this.setState({
	      visiblePhoto: false,
	    });
	}

	handleOk = () => {
		this.setState({
	      visiblePhoto: false,
	    });
	}

	staffPhotoShow = () => {
		this.setState({
	      visiblePhoto: true,
	    });
	}
  render () {
    const { modalVisible,updateModalVisible,updateFormValues,requestModelName } = this.state;
    const parentMethods = {
        handleModalVisible: this.handleModalVisible,
        dispatch: this.props.dispatch,
        requestModelName,
    }
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      dispatch: this.props.dispatch,
    	requestModelName,
    };
	  return (
	    <PageHeaderWrapper title="机构图">
			<Card bordered={false}>
				<div className={styles.proOrganTree}>
			     	<div ref={ref => (this.orgTree = ref)}/>
 				</div>
			</Card>
      <OrganTreeCreateForm {...parentMethods} modalVisible={modalVisible} />
      <OrganTreeUpdateForm
      {...updateMethods}
      updateModalVisible={updateModalVisible}
      values={updateFormValues}
      />
	    </PageHeaderWrapper>
	  )
  }
}

export default StaffCreateForm;
